package com.atsmart.app.activity;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.adapter.LoadingAdapter;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.model.CommonBody;
import com.atsmart.app.model.MessageDetail;
import com.atsmart.app.model.MessageInfo;
import com.atsmart.app.model.MessageListInfo;
import com.atsmart.app.model.MessagePageInfo;
import com.atsmart.app.model.NumberResponseInfo;
import com.atsmart.app.model.ReqMessage;
import com.atsmart.app.utils.IntentUtil;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceAsynTask;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.google.json.Gson;
import com.google.json.JsonParseException;

public class MessageDetailActivity extends BaseActivity implements
		OnClickListener {
	private static final String TAG = MessageDetailActivity.class.getName();
	MessageInfo choosen;
	TextView sendDate, sender, finshtasktitle;
	TextView Content;
	LinearLayout Confile;
	private Button btnWrite;
	private Button refresh;
	String[] sheets;
	private LayoutInflater mInflater;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_detail);
		btnWrite = (Button) findViewById(R.id.btn_history);
		btnWrite.setBackgroundResource(R.drawable.btn_write_selector);
		btnWrite.setPadding(5, 0, 5, 0);
		btnWrite.setVisibility(View.VISIBLE);
		refresh = (Button) findViewById(R.id.btn_refresh);
		this.mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		choosen = (MessageInfo) getIntent().getSerializableExtra(
				MessageListActivity.Ser_Key);
		if (choosen == null) {
			finish();
		}

		finshtasktitle = (TextView) findViewById(R.id.finshtasktitle);

		sendDate = (TextView) findViewById(R.id.sendDate);
		sender = (TextView) findViewById(R.id.sender);
		Content = (TextView) findViewById(R.id.Content);
		Confile = (LinearLayout) findViewById(R.id.confiles);
		sender.setText(choosen.getSender());
		sendDate.setText(choosen.getDate());
		finshtasktitle.setText(choosen.getTitle());
		getData();
		refresh.setOnClickListener(this);
		btnWrite.setOnClickListener(this);
	}

	// webView.loadData(URLEncoder.encode(data, encoding), mimeType, encoding);

	private void getData() {
		showLoading();
		registerLoadStatus(TAG);
		new ServiceAsynTask<MessageDetail>() {

			@Override
			protected MessageDetail callService() throws IOException,
					JsonParseException, AssertionError, BizException ,Exception{

				ReqMessage req = new ReqMessage();
				req.setId(choosen.getId());
				Gson gson = new Gson();
				return ServiceHelper.getInstance().postData(
						ServiceHost.getMsgDetail(), gson.toJson(req),
						MessageDetail.class);
			}

			@Override
			protected void runWithResult(MessageDetail result) throws Exception {
				if (result != null) {
					Confile.removeAllViews();
					Spanned text = Html.fromHtml(result.getContent());
					Content.setText(text);
					if (choosen.getFile_flg() == 1) {
						String htmlfiles = "";
						String files = result.getFile_path();
						sheets = files.split(";");
						for (int i = 0; i < sheets.length; i++) {
							View convertView = mInflater.inflate(
									R.layout.gallery_item, null);

							TextView filename = (TextView) convertView
									.findViewById(R.id.tv_gallery);
							ImageView fileview = (ImageView) convertView
									.findViewById(R.id.iv_grallery1);
							fileview.setScaleType(ScaleType.CENTER_CROP);
							filename.setText("附件" + (i + 1));
							fileview.setImageResource(R.drawable.btn_write);
							convertView.setTag(i);
							LinearLayout.LayoutParams searchParams = new LinearLayout.LayoutParams(
									LinearLayout.LayoutParams.WRAP_CONTENT,
									LinearLayout.LayoutParams.WRAP_CONTENT);
							searchParams.leftMargin = 20;
							convertView
									.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View arg0) {
											// TODO Auto-generated method stub
											int num = (Integer) arg0.getTag();
											Uri uri = Uri.parse(sheets[num]);
											Intent downloadIntent = new Intent(
													Intent.ACTION_VIEW, uri);
											startActivity(downloadIntent);

										}

									});

							Confile.addView(convertView, searchParams);
						}
						System.out.println(htmlfiles);

					}

				}

				finishedLoad(TAG);
				// hideLoading();
			}

			@Override
			protected void runWithError(MessageDetail result, int iErrorCode)
					throws Exception {

				loadingFailed(TAG, iErrorCode);
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				try{
					getDataByUrl2();
				}catch (Exception e) {
				}
			}
		}.execute();
	}

	private void getDataByUrl2() {
		showLoading();
		registerLoadStatus(TAG);
		new ServiceAsynTask<MessageDetail>() {

			@Override
			protected MessageDetail callService() throws IOException,
					JsonParseException, AssertionError, BizException ,Exception{

				ReqMessage req = new ReqMessage();
				req.setId(choosen.getId());
				Gson gson = new Gson();
				return ServiceHelper.getInstance().postData(
						ServiceHost.getMsgDetail(), gson.toJson(req),
						MessageDetail.class);
			}

			@Override
			protected void runWithResult(MessageDetail result) throws Exception {
				if (result != null) {
					Confile.removeAllViews();
					Spanned text = Html.fromHtml(result.getContent());
					Content.setText(text);
					if (choosen.getFile_flg() == 1) {
						String htmlfiles = "";
						String files = result.getFile_path();
						sheets = files.split(";");
						for (int i = 0; i < sheets.length; i++) {
							View convertView = mInflater.inflate(
									R.layout.gallery_item, null);

							TextView filename = (TextView) convertView
									.findViewById(R.id.tv_gallery);
							ImageView fileview = (ImageView) convertView
									.findViewById(R.id.iv_grallery1);
							fileview.setScaleType(ScaleType.CENTER_CROP);
							filename.setText("附件" + (i + 1));
							fileview.setImageResource(R.drawable.btn_write);
							convertView.setTag(i);
							LinearLayout.LayoutParams searchParams = new LinearLayout.LayoutParams(
									LinearLayout.LayoutParams.WRAP_CONTENT,
									LinearLayout.LayoutParams.WRAP_CONTENT);
							searchParams.leftMargin = 20;
							convertView
									.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View arg0) {
											// TODO Auto-generated method stub
											int num = (Integer) arg0.getTag();
											Uri uri = Uri.parse(sheets[num]);
											Intent downloadIntent = new Intent(
													Intent.ACTION_VIEW, uri);
											startActivity(downloadIntent);

										}

									});

							Confile.addView(convertView, searchParams);
						}
						System.out.println(htmlfiles);

					}

				}

				finishedLoad(TAG);
				// hideLoading();
			}

			@Override
			protected void runWithError(MessageDetail result, int iErrorCode)
					throws Exception {

				loadingFailed(TAG, iErrorCode);
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				finish();
			}
		}.execute();
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.btn_refresh) {
			if (BizApp.getInstance().isNetworkAvailable()
					|| BizApp.getInstance().isWiFiActive()) {
				showLoading();

				getData();

			}
		} else if (v.getId() == R.id.btn_history) {
			IntentUtil.redirectToNext(MessageDetailActivity.this,
					SendMsgActivity.class);
		}
	}

}
